﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：EnumParseModelBinder.cs
// 功能描述：TongTongMall.MallWeb
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using TongTongMall.MallWeb.Core.Enums;
using TongTongMall.UI;

namespace TongTongMall.MallWeb.WebApi.Core.ModelBinders
{
    public class EnumParseModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (!Regex.IsMatch(value.RawValue.ToString(), @"\d+"))
            {
                throw new UserFriendlyException((int)ErrCode.ParamErr, "错误的枚举类型");
            }
            try
            {
                bindingContext.Model = Enum.Parse(bindingContext.ModelType, value.RawValue.ToString());

                if (!bindingContext.ModelType.IsEnumDefined(bindingContext.Model))
                {
                    throw new UserFriendlyException((int)ErrCode.ParamErr, "错误的枚举类型");
                }
            }
            catch
            {
                throw new UserFriendlyException((int)ErrCode.ParamErr, "错误的枚举类型");
            }
            return true;
        }
    }
}